﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ECube.Org.Repositories;
using ECube.Org.Models;
namespace ECube.Org.Repositories.SqlServer
{
    public class SqlServerOrganizationRepository : IOrganizationRepository
    {

        private readonly OrgDataContext context;       

        public SqlServerOrganizationRepository(OrgDataContext context)
        {
            this.context = context;            
        }

        #region IOrganizationRepository 成员

        public IEnumerable<Organization> GetOrganizations()
        {
            IQueryable<BASOrganization> query = from p in context.BASOrganization select p;
            return projectOrgs(query).ToArray();
        }

        public Organization GetOrganization(int id)
        {
            IQueryable<BASOrganization> query =
               from p in context.BASOrganization
               where p.Id == id
               select p;

            return projectOrgs(query).FirstOrDefault();
        }

        public Organization Save(Organization org)
        {
            BASOrganization orgToSave = null;

            if (org.Id >= 0)
                orgToSave = context.BASOrganization.FirstOrDefault(p => p.Id == org.Id);

            if (orgToSave == null)
            {
                orgToSave = new BASOrganization();
                context.BASOrganization.InsertOnSubmit(orgToSave);
            }
            orgToSave.ParentId=org.ParentId;
            orgToSave.Name=org.Name ?? "";
            orgToSave.FullName=org.FullName??"";
            orgToSave.Address = org.Address??"";
            orgToSave.Fax = org.Fax??"";
            orgToSave.Telephone = org.Telephone??"";
            orgToSave.WebSite = org.WebSite??"";
            orgToSave.Status = org.Status;
            orgToSave.Description = org.Description??"";
                                                                               
            context.SubmitChanges();
            return GetOrganization(org.Id);
        }

        public bool Remove(int id)
        {
            BASOrganization foundOrg = context.BASOrganization.FirstOrDefault(p => p.Id == id);
            context.BASOrganization.DeleteOnSubmit(foundOrg);
            
                context.SubmitChanges();
                return true;
               
        }

        #endregion

        #region Private Methods

        private IEnumerable<Organization> projectOrgs(IQueryable<BASOrganization> orgs)
        {
            return (
                from p in orgs
                select new Models.Organization(p.Id,p.ParentId,p.Name,p.FullName,p.Address,p.Telephone,p.Fax,p.WebSite,p.Status,p.Description)
                ).ToArray();
        }

        #endregion
    }
}
